package com.allen.study.filter;

import cn.hutool.core.util.StrUtil;
import com.allen.study.common.constant.CacheConstants;
import com.allen.study.common.constant.SecurityConstants;
import com.allen.study.common.constant.TokenConstants;
import com.allen.study.common.exception.CustomRuntimeException;
import com.allen.study.common.utils.StringUtils;
import com.allen.study.common.utils.jwt.JwtUtils;
import com.allen.study.common.utils.redis.RedisUtils;
import com.allen.study.properties.IgnoreWhiteProperties;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName: JwtAuthFilter
 * @Author: AllenSun
 * @Date: 2025/3/15 22:48
 */
@Component
@Slf4j
public class JwtAuthFilter implements GlobalFilter, Ordered {

    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private JwtUtils jwtUtils;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        log.info("开始认证token：{}",url);
        // 跳过白名单不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            log.info("白名单路径，结束认证：{}",url);
            return chain.filter(exchange);
        }
        String token = getToken(request);
        // token令牌为空
        if (StringUtils.isEmpty(token)) {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        // Jwt
        Claims claims = jwtUtils.extractAllClaims(token);
        if (claims == null) {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }
        // 判断是否过期
        if (jwtUtils.isTokenExpired2(token)) {
            return unauthorizedResponse(exchange, "登录状态已过期");
        }
        // userid或者username为空的
        // String userid = jwtUtils.getUserId(claims);
        String username = claims.getSubject();
        if (StringUtils.isEmpty(username)) {
            return unauthorizedResponse(exchange, "令牌验证失败");
        }
        log.info("完成认证token：{}",url);
        // 设置用户信息到请求
        // addHeader(mutate, SecurityConstants.USER_KEY, userkey);
        // addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid);
        addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username);
        // 内部请求来源参数清除
        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        // String valueEncode = ServletUtils.urlEncode(valueStr);
        String valueEncode = null;
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        String failAuthMsg = StrUtil.format("鉴权异常：{}，请求路径:{}", msg, exchange.getRequest().getPath());
        log.error(failAuthMsg);
        // return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED);
        throw new CustomRuntimeException(failAuthMsg);
    }

    /**
     * 获取缓存key
     */
    private String getTokenKey(String token)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
        {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

    @Override
    public int getOrder()
    {
        return -200;
    }
}
